<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="提交人" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入提交人"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="提交时间" prop="queryTime">
        <el-date-picker
          clearable
          v-model="queryParams.queryTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          value-format="yyyy-MM-dd"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="周报归属" prop="queryValue">
        <el-select
          :visible="true"
          v-model="queryParams.queryValue"
          placeholder="操作类型"
          clearable
        >
          <el-option
            v-for="dict in dict.type.erp_weekly_query"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['erp:weekly:add']"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="weeklyList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="提交时间"
        align="center"
        prop="submitTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.submitTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="本周进展" align="center" prop="userName" />
      <el-table-column label="本周进展" align="center" prop="weeklyContent" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="toWeekDetails(scope.row)"
            v-hasPermi="['erp:weekly:edit']"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改周报数据对话框 -->
    <el-drawer
      :title="title"
      direction="rtl"
      :visible.sync="visible"
      size="54%"
      append-to-body
      :before-close="handleClose"
      :wrapperClosable="false"
    >
      <el-card class="box-card" style="width: 96%; margin-left: 20px">
        <el-form ref="form" :model="form" :rules="rules" style="width: 80%">
          <el-form-item label="姓名">
            <el-input
              readonly
              :value="$store.getters.name"
              placeholder="请输入本周进展"
            />
          </el-form-item>
          <el-form-item label="上周计划">
            <el-input
              v-model="lastWeekData.lastWeekPlanned"
              readonly
              type="textarea"
              placeholder="您上周没有填写计划"
              autosize
            />
          </el-form-item>
          <el-form-item label="本周进展" prop="weeklyContent">
            <el-input
              v-model="form.weeklyContent"
              type="textarea"
              placeholder="请输入本周进展"
              :rows="5"
            />
          </el-form-item>
          <el-divider>下周计划</el-divider>
          <el-form-item label="周一" prop="day1">
            <el-input
              v-model="form.day1"
              type="textarea"
              placeholder="请输入内容"
            />
          </el-form-item>
          <el-form-item label="周二" prop="day2">
            <el-input
              v-model="form.day2"
              type="textarea"
              placeholder="请输入内容"
            />
          </el-form-item>
          <el-form-item label="周三" prop="day3">
            <el-input
              v-model="form.day3"
              type="textarea"
              placeholder="请输入内容"
            />
          </el-form-item>
          <el-form-item label="周四" prop="day4">
            <el-input
              v-model="form.day4"
              type="textarea"
              placeholder="请输入内容"
            />
          </el-form-item>
          <el-form-item label="周五" prop="day5">
            <el-input
              v-model="form.day5"
              type="textarea"
              placeholder="请输入内容"
            />
          </el-form-item>
          <el-form-item label="周六" prop="day6">
            <el-input
              v-model="form.day6"
              type="textarea"
              placeholder="请输入内容"
            />
          </el-form-item>
          <el-form-item label="周日" prop="day7">
            <el-input
              v-model="form.day7"
              type="textarea"
              placeholder="请输入内容"
            />
          </el-form-item>
          <el-form-item label="分享人列表" prop="shareList">
            <el-select
              v-model="form.shareList"
              filterable
              clearable
              multiple
              placeholder="请选择分享人列表"
              style="width: 100%"
            >
              <el-option
                v-for="item in options"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('1')">提交</el-button>
            <el-button @click="submitForm('0')">暂存</el-button>
          </el-form-item>
        </el-form>
        <span style="color: red">温馨提示：</span>
        <div style="font-size: 14px">
          分享人请选择：卢小安，熊军凯，黄红平，朱小琴，刘宁，刘珂暘，黄宪平，丰雅伟，龚志伟，金静及本部门同事和与之相关业务的同事
        </div>
      </el-card>
    </el-drawer>

    <weeklyDetailsDrawer
      ref="weeklyDetailsDrawer"
      :userList="options"
    ></weeklyDetailsDrawer>
  </div>
</template>

<script>
import {
  listWeekly,
  getWeekly,
  delWeekly,
  addWeekly,
  getLatestWeekly,
} from "@/api/erp/weekly";

import { getUserListByStatus } from "@/api/system/user";

import weeklyDetailsDrawer from "./weeklyDetailsDrawer.vue";

export default {
  name: "Weekly",
  dicts: ["erp_weekly_query"],
  components: {
    weeklyDetailsDrawer,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 周报数据表格数据
      weeklyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      visible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        queryValue: '0',
        userName: "",
        queryTime: [],
      },
      // 表单参数
      form: {
        weeklyId: null,
        weeklyContent: null,
        day1: null,
        day2: null,
        day3: null,
        day4: null,
        day5: null,
        day6: null,
        day7: null,
        shareList: [],
        submitTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        weeklyStatus: null,
        delFlag: null,
      },
      lastWeekData: {},
      options: [],
      rules: {
        weeklyContent: [
          {
            required: true,
            message: "请输入本周进度",
            trigger: "blur",
          },
        ],
        shareList: [
          {
            required: true,
            message: "请选择分享列表",
            trigger: "change",
          },
        ],
      },
    };
  },
  created(){
    if(this.$route.query.weeklyId){
      this.$nextTick(() => {
        this.toWeekDetails({weeklyId: this.$route.query.weeklyId})
      })
    }
  },
  methods: {
    toWeekDetails(row) {
      this.$refs.weeklyDetailsDrawer.open(row.weeklyId);
    },
    getUserListByStatus() {
      getUserListByStatus({ status: "0" }).then((res) => {
        this.options = res.data;
      });
    },
    handleClose() {
      if (this.$route.query.visible || this.$route.query.weeklyId) {
        this.$router.replace({
          path: this.$route.path,
          query: {},
        });
      }
      this.visible = false;
    },
    init(){
      this.getList()
      this.getUserListByStatus()
    },
    /** 查询周报数据列表 */
    getList() {
      this.loading = true;
      listWeekly(this.queryParams).then((response) => {
        this.weeklyList = response.rows;
        this.total = response.total;
        this.loading = false;

        if (this.$route.query.queryValue) {
          this.$router.replace({
            path: this.$route.path,
            query: {},
          });
        }
      });
    },
    // 取消按钮
    cancel() {
      this.visible = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        weeklyId: null,
        weeklyContent: null,
        day1: null,
        day2: null,
        day3: null,
        day4: null,
        day5: null,
        day6: null,
        day7: null,
        shareList: [],
        submitTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        weeklyStatus: null,
        delFlag: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.queryValue = '0'
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.weeklyId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    getWeeklyInfo() {
      getLatestWeekly({ weeklyStatus: "0" }).then((res) => {
        if (res.data) {
          this.form = res.data;
          this.form.shareList = res.data.shareList ? res.data.shareList.split(",") : null;
        }
      });
    },
    getLatestWeekly() {
      getLatestWeekly({ weeklyStatus: "1" }).then((res) => {
        if (res.data) {
          this.lastWeekData = res.data;
          this.form.shareList = res.data.shareList ? res.data.shareList.split(",") : null;
          this.lastWeekData.lastWeekPlanned =
            "周一：" + (res.data.day1 || '今日无计划') +
            "\n" +
            "周二：" + (res.data.day2 || '今日无计划') +
            "\n" +
            "周三：" + (res.data.day3 || '今日无计划') +
            "\n" +
            "周四：" + (res.data.day4 || '今日无计划') +
            "\n" +
            "周五：" + (res.data.day5 || '今日无计划') +
            "\n" +
            "周六：" + (res.data.day6 || '今日无计划') +
            "\n" +
            "周日：" + (res.data.day7 || '今日无计划');
        } else {
          if (!this.form.shareList || this.form.shareList.length === 0) {
            this.form.shareList = [
              "65315650692447",
              "113030515728601022",
              "090157122440088021",
              "071328165826147062",
              "1755536800674921",
              "041311204721141294",
              "012227523739810509",
              "01083459565620452138",
              "0345446612759419865",
              "66545605321195944",
            ];
          }
        }
      });
    },

    /** 新增按钮操作 */
    async handleAdd() {
      this.reset();
      await this.getWeeklyInfo();
      await this.getLatestWeekly();
      this.visible = true;
      this.title = "添加周报数据";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const weeklyId = row.weeklyId || this.ids;
      getWeekly(weeklyId).then((response) => {
        this.form = response.data;
        this.visible = true;
        this.title = "修改周报数据";
      });
    },
    /** 提交按钮 */
    submitForm(weeklyStatus) {
      if (weeklyStatus === "1") {
        this.$confirm("提交后将无法修改, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.submit(weeklyStatus);
        });
      } else {
        this.submit(weeklyStatus);
      }
    },
    submit(weeklyStatus) {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.weeklyStatus = weeklyStatus;
          this.form.shareList = this.form.shareList?.join(",");
          this.form.deviceFlag = '0' // pc 端标识
          addWeekly(this.form).then((response) => {
            this.$modal.msgSuccess("提交成功");
            this.visible = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const weeklyIds = row.weeklyId || this.ids;
      this.$modal
        .confirm('是否确认删除周报数据编号为"' + weeklyIds + '"的数据项？')
        .then(function () {
          return delWeekly(weeklyIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "erp/weekly/export",
        {
          ...this.queryParams,
        },
        `weekly_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
